from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

#from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from myapp.myser import *
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

from myapp.models import *

from dwebsocket.decorators import accept_websocket
import uuid
from myapp.models import User
import redis
import base64
from hashlib import sha256
import hmac
import urllib
# 导入MongoDB
import pymongo
# 建立mongo的链接对象
mongo_client = pymongo.MongoClient(host='localhost', port=27017)
# 导入bson库 as起别名
from bson import json_util as jsonb

import redis
# 定义IP地址和端口
host = '127.0.0.1'
port = 6379
# 定义链接对象
r = redis.Redis(host=host, port=port)

# 对结果集美化方法
def dictfetchall(cursor):
    # 获取游标描述
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))  # 列表推导时 行转列
        for row in cursor.fetchall()
    ]

# 商品关注接口（查询用户关注过的商品列表）
class UidFlows(View):
    def get(self, request):
        uid = request.GET.get('uid', None)

        # 建立游标对象
        cursor = connection.cursor()

        # 执行sql语句  查询用户关注的商品
        cursor.execute('select a.id from goods a left join userflow b on a.id = b.gid where b.uid = %s' % str(uid))

        # 美化结果
        res = dictfetchall(cursor)

        # 返回结果  手动序列化 防止中文乱码   default=str,时间格式转为字符串
        return HttpResponse(json.dumps(res, ensure_ascii=False, indent=4, default=str), content_type='application/json')


class GetFlows(View):
    def get(self, request):
        # 商品ID
        id = request.GET.get('id', None)
        # 用户ID
        uid = request.GET.get('uid', None)
        # 判断取关还是关注  0为取关  1关注
        type = request.GET.get('type', 1)

        if int(type) == 1:
            # 关注
            userflow = UserFlow(gid=int(id), uid=int(uid))
            try:
                userflow.save()
                msg = '关注成功'
                # 设置时间
                r.set(str(uid), '123')
                r.expire(str(uid), 180)  # 防止恶意评论

                # 查询商品  关注数加1并保存
                goods = Goods.objects.filter(id=int(id)).first()
                goods.flow = goods.flow + 1
                goods.save()
            except Exception as e:
                print(str(e))
                return Response({'msg': '不能重复关注'})

        elif int(type) == 0:
            # 单独取关
            UserFlow.objects.filter(gid=int(id), uid=int(uid)).delete()  # 删除
            msg = '取关成功'
            # 设置时间
            r.set(str(uid), '123')
            r.expire(str(uid), 180)  # 防止恶意评论

            # 查询商品  关注数减1并保存
            goods = Goods.objects.filter(id=int(id)).first()
            goods.flow = goods.flow - 1
            goods.save()

        else:
            # 批量取关
            ids = request.GET.get('ids', None)
            # 批量操作
            UserFlow.objects.filter(uid=int(uid)).delete()
            # 强转 eval语义化
            id_list = eval(ids)
            # 遍历重新关注
            for id in id_list:
                userflow = UserFlow(gid=int(id), uid=int(uid))
                userflow.save()
            msg = '批量删除关注成功'
            # 设置时间
            r.set(str(uid), '123')
            r.expire(str(uid), 180)  # 防止恶意评论

        return Response({'msg': msg})


# # 标签
# class Tags(View):
#     def get(self, request):
#         id = request.GET.get('id', None)
#
#         # 建立数据库对象
#         db = mongo_client.md
#         # 建立表对象
#         table = db.mytag
#
#         # 查询数据
#         res = table.find_one({'gid': str(id)})
#         return HttpResponse(jsonb.dumps(res, ensure_ascii=False))  #  中文不能编译 ensure_ascii=False 防止中文转换，以免除乱码
#
# # 商品标签添加接口  MongoDB
# class AddTags(APIView):
#     def get(self, request):
#         # 接收商品数据
#         id = request.GET.get('id', None)
#         tags = request.GET.get('tags', None)
#         # print(tags)
#         tags = tags.split(",")  # 字符串转换成list与MongoDB吻合
#
#         # 建立数据库对象
#         db = mongo_client.md
#         # 建立表对象
#         table = db.mytag
#
#         # 排重操作
#         # 查询
#         res = table.find({'gid': str(id)}).count()  # 查询count数量
#         if res > 0:
#             return Response({'code': 300, 'msg': '重复数据'})
#         else:
#             # 入库操作
#             table.insert({'gid': str(id), 'tags': tags})
#             return Response({'code': 200, 'msg': '入库成功'})
#
# # 商品展示
# class Good(APIView):
#     def get(self, request):
#         # 当前页
#         page = int(request.GET.get('page', 1))
#         # 一页多少条商品
#         size = int(request.GET.get('size', 2))
#         # 定义从哪开始切
#         data_start = (page - 1) * size
#         # 定义切到哪
#         data_end = page * size
#
#         # 查询数据
#         goodslist = Goods.objects.all()[data_start:data_end]
#         # 查询总数量
#         count = Goods.objects.count()
#
#         # 序列化
#         goods_ser = GoodsSer(goodslist, many=True)
#         res = {}
#         res['total'] = count  # 返回总数
#         res['data'] = goods_ser.data  # 返回数据
#         return Response(res)
#
#
# # 添加商品
# class AddGos(APIView):
#     def get(self, request):
#         name = request.GET.get('name', 'null')
#         price = request.GET.get('price', 'null')
#         cate_id = request.GET.get('cate_id', 'null')
#         # 排重
#         goods = Goods.objects.filter(name=name).first()
#
#         if goods:
#             res = {}
#             res['code'] = 405
#             res['msg'] = '该商品已存在'
#             return Response(res)
#
#         # 入库
#         goods = Goods()
#         goods.name = name
#         goods.price = price
#         goods.save()
#
#         # 查询商品ID
#         goods = Goods.objects.filter(name=name).first()
#
#         res = {}
#         res['code'] = 200
#         res['id'] = goods.id
#         res['msg'] = '恭喜， 添加成功'
#
#         return Response(res)
#
#
#
#
#
#
# # 定义七牛云存储接口
# from qiniu import Auth
#
# class QiniuKen(APIView):
#     def get(self, request):
#         # 定义秘钥
#         # q = Auth('AK', 'SK')
#         q = Auth('TMp1YYt7ec0baD7o1JBOF6hYCmmJ8TXGbdi6LM_A',
#                  'igx1uly_3n16slUxXWvZy0Abe9lQCwhwlfNMLJUZ'
#                  )
#         # 指定上传空间
#         # token = q.upload_token('空间名称')
#         token = q.upload_token('upload9')
#         # print(token)  # token 上传文件的凭证、令牌
#         # 返回前端
#         res = {}
#         res['token'] = token
#         return Response(res)
#
#
# #装饰器(判断用户身份）
# def log():
#     def decorator(func):
#         def wrapper(self, request, *args, **kwargs):
#             #判断jwt逻辑
#             uid = request.GET.get("uid")
#             clinet_jwt = request.GET.get("jwt",None)
#             if clinet_jwt == None:
#                 return HttpResponse('你没有带上令牌')
#             decode_jwt = jwt.decode(clinet_jwt, '123', algorithms=['HS256'])
#             if decode_jwt['uid'] != str(uid):
#                 return HttpResponse('你篡改了用户id')
#             return func(self, request, *args, **kwargs)
#         return wrapper
#     return decorator
#
#
# class QiniuUser(APIView):
#     # @log()    #判断用户身份（用时解开注释）
#     def get(self, request):
#         uid = request.GET.get('uid')
#         # 查询数据
#         user = User.objects.filter(id=uid).first()
#         # 序列化对象
#         user_ser = UserSer(user)
#         res = user_ser.data
#         return Response(res)
#
#
#
#
#
#
#
#
#
# # 注册
# class RegView(APIView):
#     def get(self, request):
#         username = request.GET.get('username', 'null')
#         password = request.GET.get('password', 'null')
#         # 排重
#         user = User.objects.filter(username=username).first()
#         if user:
#             return Response({
#                 'code': 500,
#                 'mes': '已经注册过'
#             })
#         # 注册新用户
#         user = User(username=username, password=password)
#         user.save()
#         return Response({
#             'code': 200,
#             'mes': '注册成功'
#         })
#
# # 登录
# class LoginView(APIView):
#     def get(self, request):
#         # 接收参数
#         username = request.GET.get('username', 'null')
#         password = request.GET.get('password', 'null')
#         # 查询数据
#         user = User.objects.filter(username=username, password=password).first()
#         # 判断
#         if user:
#             res = {}
#             res['code'] = 200
#             res['msg'] = '登录成功'
#             return Response(res)
#         else:
#             res = {}
#             res['code'] = 405
#             res['msg'] = '登录失败'
#             return Response(res)
#
# # 钉钉登录
# def DingDingLogin(request):
#     code = request.GET.get('code')
#     t = time.time()
#     # 时间戳
#     timestamp = str((int(round(t * 1000))))
#     appSecret = 'kFeBIcAi-P5VNeA_2EIjARQu6dYct2h-3iiTUNpPEBuWjN3efumu2BfLhBgGVttz'
#     # 构造签名
#     signature = base64.b64encode(
#         hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())
#     # 请求接口，换取钉钉用户名
#     payload = {'tmp_auth_code': code}
#     headers = {'Content-Type': 'application/json'}
#     res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
#         signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoaty1hbauyiitjsip2",
#                         data=json.dumps(payload), headers=headers)
#
#     res_dict = json.loads(res.text)
#     user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
#     dingding_id = ''
#     user_id = ''
#     if user:  # 判断该用户是否在本地库中创建过
#         dingding_id = res_dict['user_info']['nick']
#         user_id = user.id
#     else:  # 没有创建过的用户，创建
#         User.objects.create(username=str(res_dict['user_info']['nick']), password='')
#         user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
#         dingding_id = res_dict['user_info']['nick']
#         user_id = user.id
#
#     return redirect('http://localhost:8080/?dingding_id=' + str(dingding_id) + '&' + 'uid=' + str(user_id))  # 重定向到主页 并且携带uid和钉钉的用户名
